
package cup.modules.system.wrapper;

import cn.hutool.json.JSONUtil;
import cup.common.cache.DictCache;
import cup.common.cache.SysCache;
import cup.common.enums.DictEnum;
import cup.core.log.exception.ServiceException;
import cup.modules.system.vo.UserVO;
import cup.core.mp.support.BaseEntityWrapper;
import cup.core.tool.utils.BeanUtil;
import cup.core.tool.utils.Func;
import cup.modules.system.entity.Tenant;
import cup.modules.system.entity.User;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 包装类,返回视图层所需的字段
 *
 * @author
 */
public class UserWrapper extends BaseEntityWrapper<User, UserVO> {

	private static UserWrapper userWrapper = new UserWrapper();

	public static UserWrapper build() {
		return userWrapper;
	}

	public static List<UserVO> entityPublicVO(List<User> user) {
		if(CollectionUtils.isEmpty(user)){
			return new ArrayList<>();
		}
		List<UserVO> list = new ArrayList<>(user.size());
		for (User user1 : user) {
			list.add(entityPublicVO(user1));
		}
		return list;
	}

	public static UserVO entityPublicVO(User user) {
		if(null==user){
			return new UserVO();
		}
		return userWrapper.entityVO(user);
	}

	public List<UserVO> entityListVO(List<User> list) {
		List<UserVO> result = new ArrayList<>(list.size());
		if (CollectionUtils.isEmpty(list)) {
			return result;
		}
		list.forEach(x -> result.add(entityVO(x)));
		return result;
	}

	@Override
	public UserVO entityVO(User user) {
		UserVO userVO = Objects.requireNonNull(BeanUtil.copy(user, UserVO.class));
		Tenant tenant = SysCache.getTenant(user.getTenantId());
		if (null == tenant) {
			throw new ServiceException("未获取到租户信息:[" + JSONUtil.toJsonStr(user) + "]");
		}
		List<String> roleName = SysCache.getRoleNames(user.getRoleId());
		List<String> deptName = SysCache.getDeptNames(user.getDeptId());
		List<String> postName = SysCache.getPostNames(user.getPostId());
		userVO.setTenantName(tenant.getTenantName());
		userVO.setRoleName(Func.join(roleName));
		userVO.setDeptName(Func.join(deptName));
		userVO.setPostName(Func.join(postName));
		userVO.setSexName(DictCache.getValue(DictEnum.SEX, user.getSex()));
		userVO.setUserTypeName(DictCache.getValue(DictEnum.USER_TYPE, user.getUserType()));
		return userVO;
	}

}
